package com.mike.uaa.server.service.impl;

import com.mike.uaa.core.User;
import com.mike.uaa.server.domain.entity.ExUser;
import com.mike.uaa.server.repositories.mybatis.ExUserMapper;
import com.mike.uaa.server.service.UserDetailService;
import com.mike.uaa.web.Exceptions;
import com.mike.uaa.web.ResponseBuilder;
import com.mike.uaa.web.ServiceException;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * @author z zhang
 */
@Service
@RequiredArgsConstructor
public class UserDetailServiceImpl implements UserDetailService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailServiceImpl.class);
    @Autowired
    ExUserMapper exUserMapper;

    @Override
    public User loadUserByUsername(String username) {

        // TODO 模拟获取用户
//        return User.builder().id(1001)
//                .username("admin")
//                .nickname("系提管理员")
//                .password("$2b$08$/FXw0FvHG4k2xbunEFwTgOwkeireLy9oxBMNEWQkkLYuUwb8kc4si")
//                .status(1)
//                .mobile("18110011001")
//                .lastLogin(LocalDateTime.now())
//                .build();
        //真正查询数据库，获取用户信息
        ExUser exUser = exUserMapper.selectByUsername(username);
        if (StringUtils.isEmpty(exUser)){
            log.info("登录用户：{} 不存在.", username);
          throw Exceptions.createUnauthorizedException("用户不存在,请重新输入");
        }
        //构建用户对象返回
        return createUser(exUser);
    }

    public User createUser(ExUser exUser){
        return User.builder().id(Integer.valueOf(exUser.getUserId()))
                .username(exUser.getUserName())
                .nickname(exUser.getUserName())
                .password(exUser.getPassword())
                .status(1)
                .mobile(exUser.getUserPhone())
                .lastLogin(LocalDateTime.now())
                .build();
    }
}
